package com.svr.config;

import io.swagger.models.auth.In;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;

import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.*;

/**
 * @author yinbo
 */
@Configuration
public class SwaggerConfig {

	private SwaggerProperties swaggerProperties;

	@Autowired
	public void setSwaggerProperties(SwaggerProperties swaggerProperties) {
		this.swaggerProperties = swaggerProperties;
	}

	@Bean
	public Docket createApi(){
		return new Docket(DocumentationType.OAS_30)
				.pathMapping("/")
				.enable(swaggerProperties.getEnable())
				.apiInfo(apiInfo())
				.host(swaggerProperties.getTryHost())
				.select()
				.apis(RequestHandlerSelectors.any())
				.paths(PathSelectors.any())
				.build()
				.protocols(provideProtocols())
				.securitySchemes(provideSecurityScheme())
				.securityContexts(provideSecurityContext());
	}

	public ApiInfo apiInfo(){
		return new ApiInfoBuilder()
				.title(swaggerProperties.getApplicationName() + "API DOC")
				.description(swaggerProperties.getApplicationDescription())
				.contact(new Contact("WN63",null,"wn63@wnxy.com"))
				.version("Application Version : " + swaggerProperties.getApplicationVersion() + " , Spring Boot Version : "  + SpringBootVersion.getVersion())
				.build();
	}

	/**
	 * 利用一个Set集合提供支持哪些协议！！
	 * @return
	 */
	public Set<String> provideProtocols(){
		return new LinkedHashSet<>(Arrays.asList("https","http"));
	}

	/**
	 * 前后端分离的项目，用token来携带用户信息，所有的请求中基本都含有token
	 *
	 * @return
	 */
	public List<SecurityScheme> provideSecurityScheme(){
		return Collections.singletonList(new ApiKey("BASE_TOKEN","token", In.HEADER.toValue()));
	}

	public List<SecurityContext> provideSecurityContext(){
		//-- builder() 建造者设计模式 最大的特点：链式调用 XX.XX.XX.XX
		//-- 建造者模式写法的特点：类名.builder()->....(设置属性。理解为调用相应的set方法).build()
		return Collections.singletonList(SecurityContext.builder().securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN",new AuthorizationScope[]{new AuthorizationScope("global","")}))).build());
	}


}
